import React, { Component } from 'react'
import {
    Avatar, Divider, Row, Col, Input, Space, Form, message, Spin
} from 'antd'
import './StuInfo.less'
import { connect } from 'dva'
import { getCookie } from '@/utils/cookie/cookie'

const { Password } = Input
const mapStateToProps = (state) => {
    const { userInfo } = state["student"]
    const { noticeList } = state['notice']
    return { userInfo, noticeList }
}
const mapDispatchToProps = (dispatch) => {
    return {
        async getUserInfo(id) {
            const result = await dispatch({
                type: 'student/getUserInfo',
                id
            })
            return result
        },
        async updatePassword(id, prePassword, nextPassword) {
            const result = await dispatch({
                type: 'student/updatePassword',
                id, prePassword, nextPassword
            })
            return result
        },
        async updateName(id, nextName) {
            const result = await dispatch({
                type: 'student/updateName',
                id, nextName
            })
            return result
        },
        async getNotice(userId) {
            const result = await dispatch({
                type: 'notice/getNotice',
                userId
            })
        },
        async checkNotice(noticeId) {
            const result = await dispatch({
                type: 'notice/checkNotice',
                noticeId
            })
            return result
        },
        async deleted(noticeId) {
            const result = await dispatch({
                type: 'notice/deleted',
                noticeId
            })
            return result
        }
    }
}

class Index extends Component {

    formRef = React.createRef()

    constructor(props) {
        super(props)
        this.state = {
            stuName: "",
            editPassword: false,
            loadingEditPass: false
        }
        this.editPasswordEle = this.editPasswordEle.bind(this)
    }

    componentDidMount() {
        (async () => {
            const result = await this.props.getUserInfo(getCookie("userId"))
            await this.props.getNotice(getCookie("userId"))
            if (result.status !== 0 || result.code !== 200) {
                message.error("加载失败")
            } else {
                this.setState({
                    stuName: result?.data?.stuName
                })
            }
        })()
    }

    editPasswordEle() {
        return <Form ref={this.formRef} layout='inline' style={{
            height: '50px',
            width: '300px',
        }}>
            <Space size='large' align='align' style={{
                padding: '9px 0px'
            }}>
                <Form.Item label='旧密码' name='prePassword' rules={[
                    {
                        required: true,
                        message: "此处不能为空"
                    }
                ]}>
                    <Password style={{ width: '174px' }} />
                </Form.Item>
                <Form.Item label='新密码' name="nextPassword" rules={[
                    {
                        required: true,
                        message: "此处不能为空"
                    },
                    {
                        validator: () => {
                            return new Promise((resolve, reject) => {
                                const { nextPassword, nextPasswordAgain } = this.formRef.current.getFieldsValue()
                                if (nextPassword === nextPasswordAgain) {
                                    resolve()
                                } else {
                                    reject("新密码与确认密码不一致")
                                }
                            })
                        },
                        message: "新密码与确认密码不一致"
                    }
                ]}>
                    <Password style={{ width: '174px' }} onChange={(e) => {
                        this.formRef.current.validateFields()
                    }} />
                </Form.Item>
                <Form.Item label='确认密码' name="nextPasswordAgain" rules={[
                    {
                        required: true,
                        message: "此处不能为空"
                    },
                    {
                        validator: () => {
                            return new Promise((resolve, reject) => {
                                const { nextPassword, nextPasswordAgain } = this.formRef.current.getFieldsValue()
                                if (nextPassword === nextPasswordAgain) {
                                    resolve()
                                } else {
                                    reject("新密码与确认密码不一致")
                                }
                            })
                        },
                        message: "新密码与确认密码不一致"
                    }
                ]}>
                    <Password style={{ width: '174px' }} onChange={(e) => {
                        this.formRef.current.validateFields()
                    }} />
                </Form.Item>
                <Form.Item>
                    <div style={{
                        width: '100px',
                        display: 'flex',
                        justifyContent: 'center',
                        alignItems: 'center'
                    }}>
                        <Spin spinning={this.state.loadingEditPass}>
                            <Space>
                                <a onClick={() => {
                                    this.formRef.current.validateFields().then(async () => {
                                        this.setState({
                                            loadingEditPass: true
                                        })
                                        const { prePassword, nextPassword } = this.formRef.current.getFieldsValue()
                                        const result = await this.props.updatePassword(getCookie("userId"), prePassword, nextPassword)
                                        if (result.status !== 0 || result.code !== 200) {
                                            message.error("修改失败")
                                        } else {
                                            message.success("修改成功")
                                            this.setState({
                                                editPassword: false
                                            })
                                        }
                                        this.setState({
                                            loadingEditPass: false
                                        })
                                    })
                                }}>确认</a>
                                <a onClick={() => {
                                    this.setState({
                                        editPassword: false
                                    })
                                }}>取消</a>
                            </Space>
                        </Spin>
                    </div>
                </Form.Item>
            </Space>
        </Form>
    }

    render() {
        const { stuId, stuName, classNameList, noticeList } = this.props.userInfo
        return <div className="user-info">
            <div className="header" style={{
                display: 'flex',
                justifyContent: "left",
                alignItems: 'center'
            }}>
                <Avatar size={60} style={{ backgroundColor: '#1890ff' }}>{stuName?.charAt?.(0)}</Avatar>
                <h1 style={{
                    margin: '0 16px'
                }}>{stuName}</h1>
            </div>
            <Divider />
            <Space size='large' style={{ height: '50px' }}>
                <div>
                    <span>姓名：</span>
                    {stuName !== null ? [<span key="input">
                        <Input value={this.state.stuName}
                            style={{ width: '174px' }}
                            required={true}
                            onChange={(e) => {
                                this.setState({
                                    stuName: e.target.value
                                })
                            }} />
                    </span>,
                    <span key="a">
                        <a onClick={async () => {
                            if (this.state.stuName) {
                                const result = await this.props.updateName(stuId, this.state.stuName)
                                if (result.status === 0 && result.code === 200) {
                                    message.success("修改成功")
                                    this.props.getUserInfo(stuId)
                                } else {
                                    message.error("修改失败")
                                }
                            } else {
                                message.error("不能为空")
                            }
                        }}>保存</a>
                    </span>]
                        : ""}
                </div>
                <div>
                    <span>学号：</span>
                    <span>{stuId}</span>
                </div>
                <div>
                    <span>班级：</span>
                    {classNameList ? <span>{classNameList.join('、')}</span> : ""}
                </div>
            </Space>
            {this.state.editPassword ?
                this.editPasswordEle() :
                <Row className='row'>
                    <Col>密码：</Col>
                    {stuId ? [<Col key="input">
                        <Password value='*********' visibilityToggle={false} readOnly />
                    </Col>,
                    <Col key="a"><a onClick={() => {
                        this.setState({
                            editPassword: true
                        })
                    }}>修改</a></Col>] : ""}
                </Row>
            }
            <div style={{
                width: '100%',
                marginTop: "30px",
                display: 'flex',
                justifyContent: 'flex-start'
            }}>
            </div>
        </div>
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Index)
